package co.edu.uniandes.sar.beans;

import co.edu.uniandes.sar.beans.util.JsfUtil;
import co.edu.uniandes.sar.beans.util.PaginationHelper;
import co.edu.uniandes.sar.ejbs.UrgenciaFacade;
import co.edu.uniandes.sar.entidades.Urgencia;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "urgenciaBean")
@SessionScoped
public class UrgenciaBean implements Serializable {

    private Urgencia current;
    private DataModel items = null;
    @EJB
    private co.edu.uniandes.sar.ejbs.UrgenciaFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public UrgenciaBean() {
    }

    public Urgencia getSelected() {
        if (current == null) {
            current = new Urgencia();
            selectedItemIndex = -1;
        }
        return current;
    }

    private UrgenciaFacade getFacade() {
        return ejbFacade;
    }

    

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Urgencia.class)
    public static class UrgenciaBeanConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UrgenciaBean controller = (UrgenciaBean) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "urgenciaBean");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Urgencia) {
                Urgencia o = (Urgencia) object;
                return getStringKey(o.getIdUrgencia());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UrgenciaBean.class.getName());
            }
        }
    }
}
